package com.foreknow.demo13;

import com.foreknow.demo13.Student;


import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author shkstart
 * @create 2021-08-02 15:47
 */
public class ReWrDo {
    FileWriter fw = null;
    BufferedWriter bw = null;
    FileReader fr=null;
    BufferedReader br=null;

    //写文件
    public void writer(List<Student> list,String filename) {


        try {
            fw = new FileWriter(filename);
            bw = new BufferedWriter(fw);
            //对集合进行遍历
            Iterator<Student> iterator = list.iterator();
            while (iterator.hasNext()) {
                Student stu = iterator.next();
                String s1 = stu.getId() + " " + stu.getName() + " " + stu.getAge() + " " + stu.getSchool();
                //将文件写到目标文件中去
                bw.write(s1);
                //换行
                bw.newLine();
            }
//            //释放资源
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //读文件
    public List<Student> read(String filename) {
        List<Student> list=new ArrayList<>();
        try {
            //创建一个节点流
            fr=new FileReader(filename);
            br=new BufferedReader(fr);
            //先读取源文件中的一行
            String s = br.readLine();
            while (s!=null){
                //对字符串进行拆分根据空格来拆分
                String[] s1 = s.split(" ");
                String id=s1[0];
                String name=s1[1];
                int age = Integer.parseInt(s1[2]);
                String school=s1[3];
                Student stu=new Student(id,name,age,school);
                list.add(stu);
                s = br.readLine();

            }
            br.close();



        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

}
